package com.dylan.久久为功.夯实基础;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ankang
 * @date 2022/5/29 15:42
 * @description 描述
 */
public class 线程变量ThreadLocal {

    /**
     * 1. 线程内的变量
     */
    ThreadLocal<Integer> threadLocal1 = new ThreadLocal<>();
    @Test
    public void test1ThreadLocal() {
        new Thread(() -> {
            threadLocal1.set(5);
            test1ThreadLocalDo();
            threadLocal1.set(6);
            test1ThreadLocalDo();
        }).run();
    }

    private void test1ThreadLocalDo() {
        System.out.println("threadLocal1:" + threadLocal1.get());
    }

    /**
     * 子线程获取父线程的线程变量
     */
    @Test
    public void test2ThreadLocal() {
        InheritableThreadLocal<Integer> threadLocal2 = new InheritableThreadLocal<>();
        // 子线程可以获取父线程变量
        threadLocal2.set(6);
        new Thread(() -> {
            System.out.println(threadLocal2.get());
        }).run();

        // 子线程只是在初始化的时候将父线程变量复制到子线程中，所有父线程修改变量值，子线程无法感知
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(() -> {
            System.out.println(threadLocal2.get());
        });
        threadLocal2.set(7);
        executorService.execute(() -> {
            System.out.println(threadLocal2.get());
        });
    }

    /**
     * 3. 父子线程真正的共享线程变量，子线程可以获取父线程最新值
     */
    @Test
    public void test3ThreadLocal() {
        TransmittableThreadLocal<Integer> threadLocal3 = new TransmittableThreadLocal<>();
        threadLocal3.set(6);
        ExecutorService executorService = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(1));
        executorService.execute(() -> {
            System.out.println(threadLocal3.get());
        });
        threadLocal3.set(7);
        executorService.execute(() -> {
            System.out.println(threadLocal3.get());
        });
    }
}
